package com.example.ivideo_2211a.commodity

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.example.ivideo_2211a.R
import com.example.ivideo_2211a.databinding.LayoutCommondityCartBinding


class CommondityAdapter(private val commondityList: List<CommondityEntity>) :

    RecyclerView.Adapter<CommondityAdapter.CommondityViewHolder>() {
    private lateinit var onItemClickListener: OnItemClickListener

    class CommondityViewHolder(
       val binding: LayoutCommondityCartBinding,
        private val onItemClickListener: OnItemClickListener
    ) : RecyclerView.ViewHolder(binding.root) {
            fun bind(commondity: CommondityEntity) {
                binding.tvProductName.text = commondity.goods_desc
                binding.tvProductPrice.text = "¥${commondity.goods_default_price}"
                binding.tvSalesVolume.text = "月销 ${commondity.goods_sales_count} 件"
                Glide.with(binding.ivProductImage).load(commondity.goods_default_icon).into(binding.ivProductImage)
                binding.root.setOnClickListener {
                    // 跳转到商品详情页面
                    ARouter.getInstance()
                        .build("/app/GoodsDetailActivity")
                        .withInt("goodsId", commondity.id)
                        .navigation()
                    
                    // 同时调用原有的点击回调
                    onItemClickListener.onItemClick(commondity)
                }
            }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommondityViewHolder {
        return CommondityViewHolder(
            DataBindingUtil.inflate(
                LayoutInflater.from(parent.context),
                R.layout.layout_commondity_cart,
                parent,
                false
            ), onItemClickListener
        )
    }

    override fun getItemCount() = commondityList.size

    override fun onBindViewHolder(holder: CommondityViewHolder, position: Int) {
        holder.bind(commondityList[position])
    }
    interface OnItemClickListener {
        fun onItemClick( data: CommondityEntity)
    }
    fun setOnItemClickListener(listener: OnItemClickListener) {
        onItemClickListener = listener
    }
}